package com.atguigu.serein.controller;

import com.atguigu.serein.bean.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.thymeleaf.util.StringUtils;

import javax.jws.WebParam;
import javax.servlet.http.HttpSession;

/**
 * @author SeRein
 */
@Slf4j
@Controller
public class LoginController {

    @GetMapping(value = {"/login"})
    public String login() {
        log.info("login_get");
        return "login";
    }

    @PostMapping("/login")
    public String toMain(User user, HttpSession session) {
        log.info("login_post");
        log.info("user: "+user.getUsername());
        if (!StringUtils.isEmpty(user.getUsername()) && !StringUtils.isEmpty(user.getPassword())) {
            session.setAttribute("loginUser", user);
            return "redirect:/toMain";
        } else {
            return "login";
        }
    }

    @GetMapping("/toMain")
    public String MainPage(HttpSession session, Model model){
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser != null){
            System.out.println(loginUser.toString());
            return "index";
        }else {
            model.addAttribute("msg","请重新登录");
            return "login";
        }
    }
}